<?php
namespace app\index\controller;

use app\index\model\Address;
use app\index\model\Article;
use app\index\model\ArticleCate;
use app\index\model\Goods;
use think\Db;

class Index extends Base
{
    /**
     * 首页
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function index()
    {
        // 推荐的新闻
        $article = Db::name('Article')->where('is_tui|is_re', 1)->field('id,title,is_tui,is_re')->select();
        $Goods   = new Goods();
        $new     = $Goods->getGoods(['is_new' => 1], 1, 100);
        $hot     = $Goods->getGoods(['is_hot' => 1], 1, 100);
        return $this->fetch('index', ['article' => $article, 'new' => $new, 'hot' => $hot]);
    }

    /**
     * 明亚快报
     *
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function article()
    {
        if(request()->isPost()){
            $where           = input('post.');
            $where['status'] = 1;
            $list            = (new Article())->getList($where);
            $html            = $this->fetch('article_ajax', ['list' => $list]);
            return json(['code' => 200, 'data' => $html, 'msg' => '明亚快报列表']);
        }
        $cate = (new ArticleCate())->getCate();
        return $this->fetch('article', ['cate' => $cate]);
    }

    /**
     * 明亚快报-详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function article_details()
    {
        $id   = input('id');
        $item = (new Article())->getItem($id);
        return $this->fetch('article_details', ['item' => $item]);
    }

    /**
     * 分类
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function group()
    {

        return $this->fetch();
    }

    /**
     * 产品详情
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function product_details()
    {
        $goods_id = input('goods_id', 0);
        $Goods    = new Goods();
        $item     = $Goods->getGoodsItem($goods_id);
        return $this->fetch('product_details', ['item' => $item]);
    }

    /**
     * 购物车
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function card()
    {

        return $this->fetch();
    }

    /**
     * 我的
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function my()
    {
        return $this->fetch();
    }

    /**
     * 每日签到
     *
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function my_sign()
    {
        $Sing = new \app\index\model\Sign();
        if(request()->isPost()){
            $response = $Sing->addSign($this->user['id']);
            return json($response);
        }
        $date['date']       = date('Y-m-d');
        $date['year']       = date('Y', strtotime($date['date']));
        $date['month']      = date('m', strtotime($date['date']));
        $date['day']        = date('d');
        $date['start_week'] = date('w', mktime(null, null, null, $date['month'], 1, $date['year']));
        $date['days']       = date('t', strtotime($date['date']));
        $date['week']       = array('日', '一', '二', '三', '四', '五', '六');
        $sign               = $Sing->getMonthSign(['user_id' => $this->user['id']]);
        $array              = [];
        foreach($sign as $key => $value){
            $array[] = date('j', strtotime($value['create_time']));
        }
        $this->assign('data', $date);
        $this->assign('sign', join(',', $array));
        return $this->fetch();
    }

    /**
     * 我的-交易记录
     * @return mixed
     * @author   [小码哥]
     */
    public function my_money()
    {
        $type = input('type', 'all');
        switch(strtolower($type)){
            case 'one':
                //获取用户
                $money = $this->user['money'];
                $title = '可用余额';
                break;
            case 'two':
                $money = $this->user['integral'];
                $title = '交易金额';
                break;
            default:
                $money = $this->user['money'] + $this->user['integral'];
                $title = '交易记录';
                break;
        }
        return $this->fetch('my_money', ['money' => $money, 'title' => $title, 'type' => $type]);
    }

    /**
     * 我的设置
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function my_equipment()
    {

        return $this->fetch();
    }

    /**
     * 添加设备
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function my_equipment_add()
    {

        return $this->fetch();
    }

    /**
     * 提现
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function my_withdrawals()
    {

        return $this->fetch();
    }

    /**
     * 新手必读
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function my_new()
    {
        return $this->fetch();
    }

    /**
     * 推广赚钱
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function extends_money()
    {

        return $this->fetch();
    }

    /**
     * 我的专属二维码
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function extends_code()
    {
        //        $wxConfig   = config('wx');
        //        $Sign       = new Sign();
        //        $appid      = $wxConfig['appid'];
        //        $app_secret = $wxConfig['app_secret'];
        /*   if(isset($_GET['code'])){
               $code   = $_GET['code'];//获取code
               $weixin = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$app_secret}&code={$code}&grant_type=authorization_code");
               echo '<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">';
               //通过code换取网页授权access_token
               $array = json_decode($weixin, true); //对JSON格式的字符串进行编码
               if(isset($array['errcode']) && !cache('access_token')){
                   //                if(cache('refresh_token')){
                   // 刷新access_token
                   $reloadAccessToken = file_get_contents("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$appid}&grant_type=refresh_token&refresh_token=" . cache('refresh_token'));
                   $reloadAccessToken = json_decode($reloadAccessToken, true);
                   $refresh_token     = $reloadAccessToken['refresh_token'];
                   $access_token      = $reloadAccessToken['access_token'];
                   cache('access_token', $access_token, 7200);
                   cache('refresh_token', $refresh_token);
                   //                }
               }else{
                   $refresh_token = isset($array['refresh_token']) ? $array['refresh_token'] : cache('refresh_token');
                   $access_token  = isset($array['access_token']) ? $array['access_token'] : cache('access_token');
                   cache('access_token', $access_token, 7200);
                   cache('refresh_token', $refresh_token);
               }
               $param = [
                   'expire_seconds' => 2592000,
                   'action_name'    => 'QR_STR_SCENE',
                   'action_info'    => [
                       'scene' => [
                           'scene_str' => session('openid')
                       ]
                   ]
               ];
               //            dump($array);
               $Recode = cache(session('openid'));
               if(!$Recode){
                   //                 $access_token = '7_CUhhkAs1XPnsJuHKrnecKbFuDckcYeT4Lc0FrUTTRliYRGxqa68HxTgQzlEww6zWvHtwk7r9DC89JBPN4Q3lzqCLx7f5jq9smbo2lkZHfhr70LNkkuuo4HBNmZwPRRcADAEGG';
                   $response = $this->request_post("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}", $param, true);
                   //                halt($response);
                   $Recode = $response['url'];
                   cache(session('openid'), $Recode, 2592000);
               }
               return $this->fetch('extends_code', ['option' => $Recode]);
           }else{
               $Sign->getD();
           }*/
        $wxConfig   = config('wx');
        $appid      = $wxConfig['appid'];
        $app_secret = $wxConfig['app_secret'];
        if(isset($_GET['code'])){
            $code   = $_GET['code'];//获取code
            $weixin = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$app_secret}&code={$code}&grant_type=authorization_code");
            echo '<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">';
            //通过code换取网页授权access_token
            $array        = json_decode($weixin, true); //对JSON格式的字符串进行编码
            $access_token = $array['access_token'];
            dump($array);
            dump(session('openid'));
            dump(cache(session('openid')));
            $Recode = cookie('Recode');
            if(!$Recode){
                $param = [
                    'expire_seconds' => 2592000,
                    'action_name'    => 'QR_STR_SCENE',
                    'action_info'    => [
                        'scene' => [
                            'scene_str' => session('openid')
                        ]
                    ]
                ];
                dump($param);
                $response = $this->request_post("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}", $param, true);
                halt($response);
                $Recode = $response['url'];
                cookie('openid', $Recode, 2592000);
            }
            //return $this->fetch('extends_code', ['option' => $Recode]);
        }else{
            // 回调地址
            $redirect_uri = urlencode('http://yunnan.lihui11.cc/Index/Index/extends_code');
            // 类型 snsapi_base 无需授权只能获取openid、snsapi_userinfo 获取基本信息、需要授权
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
            $this->redirect($url);
        }
    }

    /**
     * 模拟post进行url请求
     *
     * @param      $url
     * @param null $data
     * @param bool $json
     *
     * @return array|mixed
     * @author   [小码哥]
     */
    function request_post($url, $data = null, $json = false)
    {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($data)){
            if($json && is_array($data)){
                $data = json_encode($data);
            }
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            if($json){ //发送JSON数据
                curl_setopt($curl, CURLOPT_HEADER, 0);
                curl_setopt($curl, CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json; charset=utf-8',
                        'Content-Length:' . strlen($data)
                    )
                );
            }
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res     = curl_exec($curl);
        $errorno = curl_errno($curl);
        if($errorno){
            return array('errorno' => false, 'errmsg' => $errorno);
        }
        curl_close($curl);
        return json_decode($res, true);
    }

    /**
     * 收货地址管理
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function my_address()
    {
        $Address = new Address();
        $lisit   = $Address->getAddressAll(['user_id' => $this->user['id']]);
        $this->assign('list', $lisit);
        return $this->fetch();
    }

    /**
     * 新增收货地址
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function my_address_add()
    {
        if(request()->isPost()){
            $param            = input('post.');
            $param['user_id'] = $this->user['id'];
            $Address          = new Address();
            $response         = $Address->addAddress($param);
            return json($response);
        }
        return $this->fetch();
    }

    /**
     * 编辑收货地址
     *
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function my_address_edit()
    {
        $Address = new Address();
        if(request()->isPost()){
            $param    = input('post.');
            $response = $Address->editAddress($param);
            return json($response);
        }
        $item = $Address->getAddressOn(input('id', 0));
        $this->assign('item', $item);
        return $this->fetch();
    }

    /**
     * 设置默认收货地址
     *
     * @return \think\response\Json
     * @author   [小码哥]
     */
    public function my_address_default()
    {
        $Address  = new Address();
        $id       = input('id', 0);
        $response = $Address->defaultAddress($id);
        return json($response);
    }

    /**
     * 删除收货地址
     *
     * @return \think\response\Json
     * @author   [小码哥]
     */
    public function my_address_del()
    {
        $id       = input('id', 0);
        $Address  = new Address();
        $response = $Address->delAddress($id);
        return json($response);
    }
}
